package util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

/**
 * 用一句话描述该文件作用
 *
 * @Author pengsamkee
 * create at 2016/11/15 18:13
 */
public class ProjectUtil {

    private static final Logger logger = LoggerFactory.getLogger(ProjectUtil.class);

    public static File getCookieFile(String cookieName) {
        return new File(System.getProperty("user.dir") + File.separator + "cookie" + File.separator + cookieName);
    }

    public static File getTemplateFile(String templateType, String templateName) {
        return new File(System.getProperty("user.dir") + File.separator + "template" + File.separator + getTemplateFileName(templateType, templateName));
    }

    public static File getSourceTemplateFile(String templateType, String templateName) {
        return new File(System.getProperty("user.dir") + File.separator + "template" + File.separator + getSourceTemplateFileName(templateType, templateName));
    }

    public static String getTemplateFileName(String templateType, String templateName) {
        return String.format("%s.%s.bean.template", templateType, templateName);
    }

    public static String getSourceTemplateFileName(String templateType, String templateName) {
        return String.format("%s.%s.bean.source.template", templateType, templateName);
    }

    public static File getExportDirectory(String directoryPath) {
        File file;
        if (StringUtils.isBlank(directoryPath)) {
            file = new File(System.getProperty("user.dir"));
        } else {
            file = new File(directoryPath);
            try {
                FileUtils.forceMkdir(file);
            } catch (IOException e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        }
        return file;
    }

    public static void sortFiles(File[] files) {
        Arrays.sort(files, (preFile, nextFile) -> {
            if (preFile.isDirectory() && !nextFile.isDirectory()) return -1;
            if (!preFile.isDirectory() && nextFile.isDirectory()) return 1;
            return preFile.getName().compareTo(nextFile.getName());
        });
    }

    public static boolean isExtensionFile(File file, String[] extensions) {
        boolean found = false;
        if (file.isFile()) {
            for (final String extension : extensions) {
                if (file.getName().endsWith(extension)) {
                    found = true;
                    break;
                }
            }
        } else {
            found = true;
        }
        return found;
    }

}
